<template>
  <div>
    <el-card>
      <div slot="header">
        <!-- {{ $router.query.id ? "修改文章" : "发布文章" }} -->
        <my-bread> {{ $route.query.id ? "修改文章" : "发布文章" }} </my-bread>
      </div>
      <el-form
        ref="articleForm"
        :model="articleForm"
        :rules="articleRules"
        class="demo-form-inline"
      >
        <el-form-item prop="title" label="标题:">
          <el-input
            style="width:400px"
            v-model="articleForm.title"
            placeholder="输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item prop="content" label="内容:">
          <quill-editor
            @blur="checkContent"
            v-model="articleForm.content"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item ref="articleForm" prop="cover" label="封面:">
          <template>
            <el-radio-group
              @change="articleForm.cover.images = []"
              v-model="articleForm.cover.type"
            >
              <el-radio :label="1">单图</el-radio>
              <el-radio :label="3">三图</el-radio>
              <el-radio :label="0">无图</el-radio>
              <el-radio :label="-1">自动</el-radio>
            </el-radio-group>
            <!-- 上传组件 -->
            <!-- 一张图 -->
            <div v-if="articleForm.cover.type === 1">
              <!-- 子传父 父传子 功能实现传参 -->
              <my-image v-model="articleForm.cover.images[0]"> </my-image>
            </div>
            <!-- 三张图 -->
            <div v-if="articleForm.cover.type === 3">
              <!-- 子传父 父传子 功能实现传参 -->
              <my-image
                v-for="i in 3"
                :key="i"
                v-model="articleForm.cover.images[i - 1]"
              >
              </my-image>
            </div>
          </template>
        </el-form-item>
        <el-form-item prop="channel_id" label="频道:">
          <my-channel v-model="articleForm.channel_id"></my-channel>
        </el-form-item>
        <el-form-item v-if="$route.query.id">
          <el-button @click="modifyArticle()" type="success"
            >修改文章
          </el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="primary" @click="releaseArticle(false)"
            >发布文章</el-button
          >
          <el-button @click="releaseArticle(true)">存储草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
//  导入 富文本 样式
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// 导入组件配置
import { quillEditor } from "vue-quill-editor";
export default {
  //  局部配置
  components: {
    // 进行组件注册
    quillEditor
  },
  data() {
    // 上传封面自定义校验
    const checkCover = (rule, value, callback) => {
      if (value.type === 1) {
        if (!value.images[0]) {
          return callback(new Error("请选择一张封面"));
        }
      }
      if (value.type === 3) {
        if (!value.images[0] || !value.images[1] || !value.images[2]) {
          return callback(new Error("请选择三张封面"));
        }
      }
      //  其他情况不必校验
      callback();
    };
    return {
      //  文章校验规则对象
      articleRules: {
        // 标题校验
        title: [
          { required: true, message: "请输入你的标题", trigger: "blur" },
          { min: 5, max: 30, message: "标题文字5-30之间", trigger: "blur" }
        ],
        //  内容校验
        content: [{ required: true, message: "请输入内容" }],
        // 校验封面图片
        cover: [{ validator: checkCover, trigger: "blur" }],
        // 校验频道
        channel_id: [
          { required: true, message: "请选择所属频道", trigger: "change" }
        ]
      },
      // imgUrl: null,
      // 文章表单对象
      //   标题
      articleForm: {
        title: null,
        cover: {
          //  封面类型
          type: 1,
          // 图片数组
          images: []
        },
        channel_id: null,
        // 文章内容
        content: null
      },
      // 富文本配置
      editorOption: {
        placeholder: "请输入文章内容",
        modules: {
          // 工具栏功能
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            ["image"]
          ]
        }
      }
    };
  },
  // 深度监听
  watch: {
    "articleForm.cover": {
      handler(newVal, oldval) {
        // $nextTick   等待dom执行完再校验
        // this.$nextTick(() => {
        //   // 触发校验
        //   this.$refs.articleForm.validateField("cover");
        // });
        this.$nextTick(() => {
          this.$refs.articleForm.validateField("cover");
          // 判断不是重置
          if (newVal.type === 1 && !newVal.images[0]) {
            this.$refs.articleForm.clearValidate("cover");
          }
        });
      },
      // 开启深度监听
      deep: true
    },
    "$route.query.id": function() {
      //  判断是否 带有id 值   进行赋值
      if (this.$route.query.id) {
        // 填充数据
        this.getArticle();
      } else {
        this.articleForm = {
          title: null,
          cover: {
            //  封面类型
            type: 1,
            // 图片数组
            images: []
          },
          channel_id: null,
          // 文章内容
          content: null
        };
        // this.$refs.articleForm.clearValidate("channel_id");
        // 方法一、 编辑页面跳转发布文章页面 清空数据和阻止 校验
        setTimeout(() => {
          this.$refs.articleForm.clearValidate(["cover", "channel_id"]);
        }, 0);
      }
    }
  },
  created() {
    // 从内容管理页面跳转到编辑页面
    if (this.$route.query.id) {
      this.getArticle();
    }
  },
  methods: {
    // 编辑文章函数
    modifyArticle() {
      this.$refs.articleForm.validate(async valid => {
        try {
          await this.$http({
            method: "put",
            url: `/articles/${this.$route.query.id}`,
            // ?后键值对传参
            parmas: {
              draft: false
            },
            // 请求体传参
            data: this.articleForm
          });
          this.$message.success("修改文章成功");
          // 跳转到内容管理页面
          this.$router.push("/article");
        } catch (e) {
          this.$message.error("修改文章失败");
        }
      });
    },
    // 获取编辑数据
    async getArticle() {
      const {
        data: { data }
      } = await this.$http.get(`/articles/` + this.$route.query.id);
      // 赋值数据
      console.log(data);
      this.articleForm = data;
    },
    // 发布文章整体表单验证校验
    releaseArticle(draft) {
      this.$refs.articleForm.validate(async valid => {
        if (valid) {
          //验证成功 进行添加 、articles
          try {
            //
            await this.$http.post(`/articles?draft=${draft}`, this.articleForm);

            // 发布成功
            this.$message.success(draft ? "存入草稿成功" : "发布文章成功");
            // 跳转到文章页面
            this.$router.push("/article");
          } catch (e) {
            // 发布失败
            this.$message.error(draft ? "存入草稿失败" : "发布文章失败");
          }
        }
      });
    },
    // 校验表单内容
    checkContent() {
      // 触发表单项中就 建明为 content v
      this.$refs.articleForm.validateField("content");
    }
  }
};
</script>

<style scoped lang="less">
/deep/ .ql-toolbar.ql-snow {
  padding: 0 8px;
}
/deep/ .ql-editor {
  height: 250px;
  tab-size: 24px;
}
</style>
